package com.googlecode.allinclusive.fw.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.googlecode.allinclusive.fw.database.ibatis.EntityManager;

/**
 * 用户信息管理服务组件
 * 
 * @author <a href="mailto:xiayg@cares.sh.cn">xiayg</a>
 * @version 1.0 2010-12-29
 */
public class AuthorityUserServiceImpl implements UserDetailsService {
	
	/**
	 * 数据存取管理对象实例(IBatis)
	 */
	@Autowired
	protected EntityManager entityManager;
	
	/**
	 * 根据给定用户名获取用户信息
	 * @param username 用户名
	 */
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		
		// 根据给定用户名获取用户信息
		User user = entityManager.executeForObject("User.getUserByName", username, User.class);
		// 用户信息不存在
		if (user == null) {
			return null;
		}

		// 用户授权
		List<Role> roles = entityManager.executeForObjectList("Role.getRoleByName", username);
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (Role role : roles) {
			GrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
			authorities.add(authority);
		}
		user.setAuthorities(authorities);
		
		return user;
	}

}
